<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="200px">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="form.name" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="pubPoker1" prop="pubPoker1">
            <el-input v-model="form.pubPoker1" style="width: 200px;" />
            <el-button type="primary" @click="randmoCardApi(1)">随机</el-button>
          </el-form-item>
          <el-form-item label="pubPoker2" prop="pubPoker2">
            <el-input v-model="form.pubPoker2" style="width: 200px;" />
            <el-button type="primary" @click="randmoCardApi(2)">随机</el-button>
          </el-form-item>
          <el-form-item label="服务器选择" prop="serverId">
            <el-select v-model="form.serverId" placeholder="请选择服务器">
              <el-option
                v-for="item in serverlistData"
                :key="item.id"
                :label="item.name"
                :value="item.id + ''"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="换牌所需基础便便数量" prop="changePokerBaseNum">
            <el-input v-model="form.changePokerBaseNum" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="每次换牌需要增加便便数量" prop="changePokerAddNum">
            <el-input v-model="form.changePokerAddNum" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="免费换牌次数" prop="activeFreeChage">
            <el-input v-model="form.activeFreeChage" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="最大换牌次数" prop="activeMaxChage">
            <el-input v-model="form.activeMaxChage" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="活动截止时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="12:00:00"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="活动名称" />
        <el-table-column prop="taskId" label="活动流水号" />
        <el-table-column prop="pubPoker1" label="公共牌1" />
        <el-table-column prop="pubPoker2" label="公共牌2" />
        <el-table-column prop="changePokerBaseNum" label="换牌基础便便" />
        <el-table-column prop="runStatus" label="活动状态" />
        <el-table-column prop="serverId" label="服务器信息">
          <template #default="{ row }">
            {{ row.serverId | getserviceName(serverlistData) }}
          </template>
        </el-table-column>
        <el-table-column prop="changePokerAddNum" label="额外换牌便便" />
        <el-table-column prop="activeFreeChage" label="免费换牌次数" />
        <el-table-column prop="activeMaxChage" label="最大换牌次数" />
        <el-table-column prop="endTime" label="活动截止时间" />
        <el-table-column v-if="checkPer(['admin','pokerActivateInfo:edit','pokerActivateInfo:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.runStatus===0||scope.row.runStatus===1"
              class="filter-item"
              size="mini"
              type="primary"
              @click="getAward(scope.row)"
            >奖励配置
            </el-button>
            <el-button
              v-if="scope.row.runStatus===0"
              class="filter-item"
              size="mini"
              type="primary"
              @click="start(scope.row)"
            >开启活动
            </el-button>
            <el-button
              v-if="scope.row.runStatus===1"
              class="filter-item"
              size="mini"
              type="primary"
              @click="end(scope.row)"
            >结算
            </el-button>
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>

        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog
      title="奖励配置"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <template>
        <el-table
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column
            prop="rank"
            label="名次"
            width="50"
          />
          <el-table-column
            prop="awardContent"
            label="奖励内容"
          >
            <template slot-scope="scope">
              <span v-for="(item, index) in scope.row.awardItems" :key="index">
                <el-tag type="info"> {{ item.name }} * {{ item.num }}</el-tag>
              </span>
            </template>>
          </el-table-column>
          <el-table-column label="删除" width="80px">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="deletAwardConfig(scope.row)" />
            </template>

          </el-table-column>
        </el-table>
      </template>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="awardAdd = true">新增奖励</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="新增奖励"
      :visible.sync="awardAdd"
      width="20%"
      :before-close="handleClose"
    >
      <template>
        排名： <el-input v-model="rank" style="width: 200px;" /><br>
        <div v-for="(ele, index) in awardContent" :key="index">
          材料： <el-select v-model="ele.goodId" filterable placeholder="请选择材料">
            <el-option
              v-for="item in goodlistData"
              :key="item.goodId"
              :label="item.goodName"
              :value="item.goodId"
            />
          </el-select><br>
          数量：<el-input v-model="ele.num" style="width: 200px;" />
        </div>
        <el-button
          @click="awardContent.push({
            goodId: '',
            num: '',
            name:''
          })"
        >新增</el-button>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="awardAdd = false">取 消</el-button>
        <el-button type="primary" @click="doAddAward">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import crudPokerActivateInfo from '@/api/system/pokerActivateInfo'
import { startActivate, randmoCard, serverList, endActivate } from '@/api/system/pokerActivateInfo'
import { goodList } from '@/api/system/pokerGoodInfo'

import { list, add, del } from '@/api/system/pokerActivateAwardInfo'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, name: null, pubPoker1: null, pubPoker2: null, changePokerBaseNum: null, changePokerAddNum: null, activeFreeChage: null, activeMaxChage: null, fontPrizeNum: null, fontPrizeNumGoodid: null, fontPrizeThirdGoodid: null, specialGoodid: null, endTime: null, serverId: null,activateType :0 }
export default {
  name: 'PokerActivateInfo',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: 'activate', url: 'api/pokerActivateInfo', idField: 'id', sort: 'id,desc', crudMethod: { ...crudPokerActivateInfo }})
  },
  data() {
    return {
      dialogVisible: false,
      awardAdd: false,
      rank: undefined,
      serverlistData: [],
      goodlistData: [],
      activateId: '',
      activateAwardId: undefined,
      awardContent: [{
        goodId: '',
        num: '',
        name: ''
      }],

      permission: {
        add: ['admin', 'pokerActivateInfo:add'],
        edit: ['admin', 'pokerActivateInfo:edit'],
        del: ['admin', 'pokerActivateInfo:del']
      },
      rules: {
        name: [
          { required: true, message: '活动名称不能为空', trigger: 'blur' }
        ],
        pubPoker1: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        pubPoker2: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        changePokerBaseNum: [
          { required: true, message: '换牌所需基础便便数量不能为空', trigger: 'blur' }
        ],
        changePokerAddNum: [
          { required: true, message: '每次换牌需要增加便便数量不能为空', trigger: 'blur' }
        ],
        activeFreeChage: [
          { required: true, message: '免费换牌次数不能为空', trigger: 'blur' }
        ],
        activeMaxChage: [
          { required: true, message: '最大换牌次数不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '活动截止时间不能为空', trigger: 'blur' }
        ]
      },
      tableData: []
    }
  },

  filters: {
    getserviceName(value, listData) {
      const item = listData.find(ele => {
        return ele.id === Number(value)
      })
      return item ? item.name : ''
    }
  },

  created() {
    this.crud.query.activateType = 0;
    this.crud.refresh();
    this.getserverList()
    this.getgoodList()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // materialsAdd() {
    //   console.log(this.awardContent, 'awardContent')
    // },
    handleClose() {
      this.dialogVisible = false
      this.activateId = ''
    },
    getAward(row) {
      this.dialogVisible = true
      console.log(row)
      const param = {
        activateId: row.id
      }
      this.activateAwardId = row.id
      this.activateId = row.id || ''
      list(param).then((res) => {
        this.tableData = res.awardList.map(item => ({
          ...item,
          awardItems: JSON.parse(item.awardContent)
        }))

        console.log(this.tableData)
      })
    },

    deletAwardConfig(row) {
      const param = {
        id: row.id
      }
      del(param).then((res) => {
        this.$message.success('删除成功')
        this.refreshAwardList()
      })
    },

    doAddAward() {
      // 检查是否已存在相同名次
      const isRankExist = this.tableData.some(item => item.rank == this.rank);

      if (isRankExist) {
        this.$message.warning('已经存在该排名，请核验');
        return;
      }

      // 填充物品名称
      this.awardContent.forEach(iteminsert => {
        if (!iteminsert.goodId) return;

        const goodItem = this.goodlistData.find(good => good.goodId === iteminsert.goodId);
        if (goodItem) {
          iteminsert.name = goodItem.goodName;
        }
      });

      // 构造参数
      const param = {
        activateId: this.activateAwardId,
        awardContent: this.awardContent,
        rank: this.rank
      };

      // 调用接口添加
      add(param).then(() => {
        this.$message.success('新增成功');
        this.refreshAwardList(); // 刷新奖励列表
        this.awardAdd = false;   // 关闭弹窗
      }).catch(() => {
        this.$message.error('新增失败');
      });
      this.rank=undefined;
      this.awardContent=[{
        goodId: '',
        num: '',
        name: ''
      }]
    },

    
    refreshAwardList() {
      const params = {
        activateId: this.activateAwardId
      }
      list(params).then((res) => {
        console.log(res,"res");
        this.tableData = res.awardList.map(item => ({
          ...item,
          awardItems: JSON.parse(item.awardContent)
        }))
      })
    },

    start(row) {
      const param = {
        id: row.id
      }
      startActivate(param).then((res) => {
        this.$message.success('活动开启成功')
        location.reload()
  
      })
    },

    end(row) {
      const param = {
        id: row.id
      }
      endActivate(param).then((res) => {
        this.$message.success('结算完成')
        location.reload()
      })
    },
    randmoCardApi(poker) {
      randmoCard().then((res) => {
        if (poker == 1) {
          this.$message.success(res)
          this.form.pubPoker1 = res
        } else if (poker == 2) {
          this.$message.success(res)
          this.form.pubPoker2 = res
        }
      })
    },

    getserverList() {
      serverList().then((res) => {
        this.serverlistData = res
      })
    },

    getgoodList() {
      goodList().then((res) => {
        this.goodlistData = res
      })
    }
  }
}
</script>

<style scoped>

</style>
